package com.nageffer.shortlink.admin.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nageffer.shortlink.admin.common.biz.user.UserContext;
import com.nageffer.shortlink.admin.common.constant.RedisCacheConstant;
import com.nageffer.shortlink.admin.common.convention.exception.ClientException;
import com.nageffer.shortlink.admin.common.enums.UserErrorCodeEnum;
import com.nageffer.shortlink.admin.dao.entity.UserDO;
import com.nageffer.shortlink.admin.dao.mapper.UserMapper;
import com.nageffer.shortlink.admin.dto.req.UserLoginReqDTO;
import com.nageffer.shortlink.admin.dto.req.UserRegisterReqDTO;
import com.nageffer.shortlink.admin.dto.req.UserUpdateReqDTO;
import com.nageffer.shortlink.admin.dto.resp.UserLoginRespDTO;
import com.nageffer.shortlink.admin.dto.resp.UserRespDTO;
import com.nageffer.shortlink.admin.service.GroupService;
import com.nageffer.shortlink.admin.service.UserService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 用户接口层实现类
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {

    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;

    private final RedissonClient redissonClient;

    private final StringRedisTemplate stringRedisTemplate;

    private final GroupService groupService;

    /**
     * 根据用户名字获取用户
     * @param username 用户名
     * @return
     */
    @Override
    public UserRespDTO getUserByUsername(String username) {
        //根据用户名查到用户信息
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, username);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        //如果为空，抛出自定义异常
        if (userDO == null){
            throw new ClientException(UserErrorCodeEnum.USER_NULL);
        }
        //返回查询到的信息
        UserRespDTO userRespDTO = new UserRespDTO();
        BeanUtils.copyProperties(userDO,userRespDTO);
        return userRespDTO;
    }

    /**
     * 查询用户名是否已经存在
     * @param username 用户名
     * @return true：用户名不存在；false：用户名存在了
     */
    @Override
    public Boolean hasUsername(String username) {
        /*
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, username);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        return userDO == null;
        */
        //使用布隆过滤器
        return !userRegisterCachePenetrationBloomFilter.contains(username);
    }

    /**
     * 用户注册
     */
    @Transactional
    @Override
    public void register(UserRegisterReqDTO registerParam) {
        //判断用户名是否重复
        if (!hasUsername(registerParam.getUsername())){
            throw new ClientException(UserErrorCodeEnum.USER_NAME_EXIST);
        }

        //使用分布式锁，防止恶意请求毫秒级触发大量请求去一个未注册的用户名
        RLock lock = redissonClient.getLock(RedisCacheConstant.LOCK_USER_REGISTER_KEY + registerParam.getUsername());
        if (!lock.tryLock()){
            //如果获取锁失败
            throw new ClientException(UserErrorCodeEnum.USER_NAME_EXIST);
        }
        try {
            //并发时，捕获出现插入重复键的异常
            int insert = baseMapper.insert(BeanUtil.toBean(registerParam, UserDO.class));
            if (insert < 1){
                throw new ClientException(UserErrorCodeEnum.USER_SAVE_ERROR);
            }
            //注册新用户后创建默认分组
            groupService.saveGroup(registerParam.getUsername(), "默认分组");
            //插入成功后添加到布隆过滤器；同时数据库层面添加唯一索，防止布隆过滤器的误判
            userRegisterCachePenetrationBloomFilter.add(registerParam.getUsername());
        } catch (DuplicateKeyException ex){
            throw new ClientException(UserErrorCodeEnum.USER_EXIST);
        }finally {
            lock.unlock();
        }
    }

    /**
     * 根据用户名修改用户信息
     */
    @Override
    public void updateUser(UserUpdateReqDTO userUpdateReqDTO) {

        //验证当前用户名是否是已经登陆的用户
        if (!Objects.equals(userUpdateReqDTO.getUsername(), UserContext.getUsername())) {
            throw new ClientException("当前登录用户修改请求异常");
        }

        LambdaUpdateWrapper<UserDO> updateWrapper = Wrappers.lambdaUpdate(UserDO.class)
                .eq(UserDO::getUsername, userUpdateReqDTO.getUsername());
        baseMapper.update(BeanUtil.toBean(userUpdateReqDTO, UserDO.class), updateWrapper);
    }

    /**
     * 用户登录
     */
    @Override
    public UserLoginRespDTO login(UserLoginReqDTO userLoginReqDTO) {
        //根据用户名查询到没有删除的用户，并查看该用户是否存在、密码是否正确
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, userLoginReqDTO.getUsername())
                .eq(UserDO::getDelFlag, 0);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        if (userDO == null){
            throw new ClientException("用户不存在！");
        }
        if (!userDO.getPassword().equals(userLoginReqDTO.getPassword())){
            throw new ClientException("密码不正确！");
        }

        //检查该用户是否已经登陆了
        Map<Object, Object> hasLoginMap = stringRedisTemplate.opsForHash().entries("login_" + userLoginReqDTO.getUsername());
        if (CollUtil.isNotEmpty(hasLoginMap)){
            //重新设置过期时间为30分钟，刷新时间。
            stringRedisTemplate.expire("login_" + userLoginReqDTO.getUsername(), 30, TimeUnit.DAYS);
            //拿到token
            String token = hasLoginMap.keySet().stream()
                    .findFirst()
                    .map(Object::toString)
                    .orElseThrow(() -> {throw new ClientException("用户登陆错误");});
            return new UserLoginRespDTO(token);
        }

        //使用uuid生成一个token
        String token = UUID.randomUUID().toString();
        //存到redis中，并设置30分钟过期时间（用户名，token，用户信息）
        stringRedisTemplate.opsForHash().put("login_" + userLoginReqDTO.getUsername(), token, JSON.toJSONString(userDO));
        //这里为了方便调试，有效期设置了30天，后续改回30分钟。
        stringRedisTemplate.expire("login_" + userLoginReqDTO.getUsername(), 30, TimeUnit.DAYS);
        return new UserLoginRespDTO(token);
    }

    /**
     * 检查用户是否登陆
     */
    @Override
    public Boolean checkLogin(String username, String token) {
        Object tokenValue = stringRedisTemplate.opsForHash().get("login_" + username, token);
        return tokenValue != null;
    }

    /**
     * 用户退出登录
     */
    @Override
    public void logout(String username, String token) {
        if (!checkLogin(username, token)){
            throw new ClientException("用户不存在或者用户没有登陆!");
        }
        stringRedisTemplate.delete("login_" + username);
    }

}
